define(['moment'], function (moment) {
    return ['$scope', '$filter', '$stateParams', 'config', 'MMWService',
    function ($scope, $filter, $stateParams, config, $MMWService) {
        $scope.machineList = [];//區域內的機台列表
        $scope.order_by_mode = { name: "machine_no", sort: false }; // 20240229 add by Alan for M#157327: 預設設備編號升序
        $scope.filter = {};

        $scope.init = function(){
            $MMWService.PNIGList = {};
            $scope.areaNo = '';
            $scope.machineList = [];
        };

        $scope.back = function(){
            $scope.$root.hideMenu();
            $scope.$root.changeProgram('home', true);
        };

        $scope.barcodeScan = function(event){
            if(event.keyCode == 13){
                $scope.search();
            }
        };

        $scope.loadAreaList = function(){
            $MMWService.showQueryListPNIG({
                page_mode: 0,
                header: [
                    {label:$filter('translate')('common.queryList.area_c'), code:'page_no'},
                    {label:$filter('translate')('common.queryList.area_n'), code:'page_name'},
                    {label:$filter('translate')('A01.is_setting'), code:'is_set', width:'110px'}
                ],
                setCondition:function(conditions){
                    //conditions.push({column_type:'17', query_mode:'0', value:'A', merge_condition_model:'AND' });
                    return conditions;
                },
                selectCode:$scope.areaNo||'',
                confirm : function(selectItem){
                    $scope.areaNo = selectItem.page_no;
                    $scope.areaName = selectItem.page_no + ' (' + selectItem.page_name + ')';
                    $scope.search();
                }
            });
        };

        $scope.search = function(){
            if($scope.areaNo != ''){
                var content = {
                    area_no    : $scope.areaNo,
                    query_mode:'10'
                };

                //20180604 modify by 李栋 for mantis#0047537
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_WIP.production_machine_info_get',
                    content : content,
                    success : function(data){
                        $scope.isSelectAll = false;
                        $scope.machineList = $filter('orderBy')($scope.machineList, 'machine_no', false); // 20231218 modify by shiwl for M#0153457: 派工排序乱序
                        $scope.machineList = data.machine_detail;
                    }
                });
            }
        };

        $scope.itemCheck = function(index, machine){
            if(machine.dispatch_mode == '0'){
                machine.dispatch_mode = machine.dispatch_mode = '1';
            }else if(machine.dispatch_mode == '1'){
                machine.dispatch_mode = machine.dispatch_mode = '0';
            }
        };

        $scope.confirm = function(){
            if($scope.machineList.length != 0){
                var content = {
                        area_no: $scope.areaNo,
                        production_machine_detail:[]
                };
                // 20240229 add by Alan for M#157327:
                // 先篩選可派工的機台        
                let machineList =  $scope.machineList.filter((machine) => machine.dispatch_mode == '0' || machine.dispatch_mode == '1');
                // 全選且篩選時，僅送出篩選後的勾選數據
                if ($scope.isSelectAll) {
                    let filtedMachineList = $scope.getPages(machineList, null, $scope.filter);
                    content.production_machine_detail = machineList
                        .map((machine) => {
                            const isMachineFilted = filtedMachineList.some((filtedMachine) => filtedMachine.machine_no === machine.machine_no);
                            // 在篩選後的勾選數據中的機台，work_mode設為0，(work_mode跟dispatch_mode相反)
                            return {
                                machine_no: machine.machine_no,
                                work_mode: isMachineFilted ? '0' : '1',
                            }
                        });
                } else {
                    content.production_machine_detail = machineList.map((machine) => {
                        return {
                            machine_no: machine.machine_no,
                            work_mode: machine.dispatch_mode === '1' ? '0' : '1', // work_mode跟dispatch_mode相反
                        }
                    });
                }

                //20180530 modify by 李栋 for mantis#0047409
                $MMWService.sendToServer({
                    uri: 'ServicesSTD.Module_EQP.dispatch_machine_set_process',
                    content : content,
                    success : function(data){
                        $scope.$root.showToast($filter('translate')('A01.msg.saveSucess'));
                    }
                });
            } else {
                $scope.$root.showAlert($filter('translate')('A01.msg.selectArea'));
            }
        }

        $scope.selectAll = function(){
            if($scope.machineList && $scope.machineList.length>0){
                $scope.isSelectAll = !$scope.isSelectAll;
                $scope.machineList.forEach(function(machine){
                    if(machine.dispatch_mode && machine.dispatch_mode != '2' && machine.dispatch_mode != '-'){
                        if($scope.isSelectAll){
                            machine.dispatch_mode = '1';
                        } else {
                            machine.dispatch_mode = '0';
                        }
                    }
                });
            }
        }
        
        $scope.orderbychange = function (mode) {
            if ($scope.order_by_mode.name != mode) {
                $scope.order_by_mode.name = mode;
                $scope.order_by_mode.sort = false;
            } else {
                if ($scope.order_by_mode.sort)
                    $scope.order_by_mode.sort = false;
                else
                    $scope.order_by_mode.sort = true;
            }
        }
        
        $scope.getPages = function (list, PageConfig, filterItem) {
            if (list) {
                if ($scope.order_by_mode.name != "")
                    list = $filter('orderBy')(list, $scope.order_by_mode.name, $scope.order_by_mode.sort);
                var temp_list = list.filter(function (item, index, array) {
                    var isOK = true,
                        keys = Object.keys(filterItem);
                    for (var i = 0; i < keys.length; i++) {
                        var key = keys[i];
                        if (isOK && item[key] != null && filterItem[key] && filterItem[key] != '') {
                            if (item[key].toString().indexOf(filterItem[key]) == -1) {
                                isOK = false;
                                break;
                            }
                        }
                    }
                    return isOK;
                });
                if (PageConfig) {
                    if (temp_list.length != 0) {
                        PageConfig.total_page = Math.ceil(temp_list.length / PageConfig.page_count);

                        if (PageConfig.page >= PageConfig.total_page) {
                            PageConfig.page = 0;
                        }
                        var index = PageConfig.page * PageConfig.page_count;
                        return temp_list.slice(index, index + PageConfig.page_count);
                    } else {
                        PageConfig.total_page = 1;
                        PageConfig.page = 0;
                    }
                } else {
                    return temp_list;
                }
            } else {

                return list;
            }
        };
    }
]});
